package com.wan.data.redis.jedis;

import cn.hutool.json.JSONUtil;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Connection;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisClientConfig;

import java.time.Duration;
import java.util.List;

public class JedisSetting extends GenericObjectPoolConfig<Connection> {
    public static final String local = "127.0.0.1";
    public static final int port = 6379;

    /** 模式 */
    private String mode;
    /** 主机和端口 */
    private List<HostAndPort> hostAndPorts;
    /** 密码 */
    private String password;
    /** 客户端名 */
    private String clientName;
    /** 数据库 */
    private int db = 0;
    /** 超时时间 */
    private int timeout = 2000;

    public JedisSetting() {
        this.setTestWhileIdle(true);
        this.setMinEvictableIdleTime(Duration.ofMillis(60000L));
        this.setTimeBetweenEvictionRuns(Duration.ofMillis(30000L));
        this.setNumTestsPerEvictionRun(-1);
        this.setMaxWait(Duration.ofMillis(3000L));
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public List<HostAndPort> getHostAndPorts() {
        return hostAndPorts;
    }

    public void setHostAndPorts(List<HostAndPort> hostAndPorts) {
        this.hostAndPorts = hostAndPorts;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public int getDb() {
        return db;
    }

    public void setDb(int db) {
        this.db = db;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public JedisClientConfig buildJedisClientConfig(){
        if(password != null && password.isEmpty()){
            this.password = null;
        }
        return DefaultJedisClientConfig.builder().clientName(this.clientName)
                .database(this.db).password(this.password)
                .timeoutMillis(this.timeout).build();
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }
}
